#include "featuredelegate.h"


#include <dtwentymodel.h>


#include <QComboBox>


FeatureDelegate::FeatureDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

QWidget *FeatureDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() != 2)
    {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
    return new QComboBox(parent);
}

void FeatureDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (!cb)
    {
        QStyledItemDelegate::setEditorData(editor, index);
        return;
    }

    QVariantMap options = qvariant_cast<QVariantMap>(index.data(DTwentyModel::Role_VALUE_OPTIONS));
    foreach (QString name, options.keys())
    {
        cb->addItem(name, options.value(name));
    }

    QVariant currentValue = index.data(Qt::EditRole);
    int comboIndex = cb->findData(currentValue);
    if (comboIndex < 0)
    {
        return;
    }

    cb->setCurrentIndex(comboIndex);
}

void FeatureDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (!cb)
    {
        QStyledItemDelegate::setModelData(editor, model, index);
        return;
    }

    QVariant value = cb->itemData(cb->currentIndex());

    model->setData(index, value, Qt::EditRole);
}


